<?php
defined('BASEPATH') or exit('No direct script access allowed');
?>
<style>
    .select2-container {
        z-index: 999999999;
    }

    .layui-layer-page .layui-layer-content {
        overflow: hidden;
    }

    .filter .title-h {
        font-size: 14px;
        border-bottom: 1px solid #dcdcdc;
        padding-bottom: 10px
    }

    .filter dl {
        position: relative;
        margin-bottom: 10px
    }

    .filter dl:after {
        content: "";
        display: block;
        clear: both
    }

    .filter dl dt {
        position: absolute;
        top: 0;
        left: 0;
        font-weight: 700
    }

    .filter dl dd {
        padding-left: 100px
    }

    .filter dl dd a {
        margin-right: 20px;
        margin-bottom: 10px;
        display: inline-block
    }

    .filter dl dd a.on {
        font-weight: 700;
        color: #477fd2
    }
</style>

<div class="row">
    <div class="col-sm-12">
        <div class="box">
            <div class="box-header with-border">
                <h3 class="box-title"> <?php if ($shop): ?> 分类 <?php echo $shop['name']; ?> 产品列表 <?php else: ?>  已售产品列表 <?php endif; ?></h3>
                <div class="pull-right">
                    <?php if ($shop): ?>
                        <input type="text" readonly="true" value="<?php echo $shop["key"]; ?>"
                               class="form-control input-sm" id="key" style="display:inline;width:180px;font-size:9px;">
                        <button data-clipboard-target="#key" class="btn btn-sm btn-warning btn-flat copybtn">复制</button>
                    <?php endif; ?>
                </div>
            </div>
            <div class="box-body">
                <div class="row">
                    <div class=" col-sm-7">
                        <!--
                                    <?php // echo anchor('admin/tbshop/import/'.$shop["id"],'采集产品','class="btn btn-sm btn-primary btn-flat"'); ?>
                                    
                                    <?php if ($isadmin == 1 || intval($permissions["shopify"]["value"]) == 1) { ?>
                                        
                                        <?php //echo anchor('admin/tbshop/apipush/'.$shop["id"],'全部发布','class="btn btn-sm btn-success btn-flat"'); ?>
                                    <?php } ?>

                                    <?php if ($isadmin == 1 || intval($permissions["shopify"]["value"]) == 1) { ?>
                                        <input type="button" class="btn btn-sm btn-primary btn-flat" value="批量生成" id="batchshopify">

                                        <input type="button" class="btn btn-sm btn-info btn-flat" value="批量发布" id="batchpush">
                                    <?php } ?>
                                    -->
                        <?php echo anchor('backend/products/shopify/' . $shop["id"], '生成CSV', 'class="btn btn-sm btn-warning btn-flat"'); ?>

                        <?php if ($shop["islock"] == 0): ?>
                            <input type="button" class="btn btn-sm btn-danger btn-flat" value="批量删除" id="batchdel">
                            <input type="button" class="btn btn-sm btn-success btn-flat" value="批量转移" id="batchtrans">
                            <input type="button" class="btn btn-sm bg-olive btn-flat" value="批量标记" id="batchtag">

                            <input type="button" class="btn btn-sm btn-warning btn-flat" value="批量推送" id="batchpush">

                            <?php echo anchor('backend/products/titlereplace/' . $shop["id"], '标题替换', 'class="btn btn-sm btn-info btn-flat"'); ?>
                            <?php echo anchor('backend/products/descreplace/' . $shop["id"], '描述替换', 'class="btn btn-sm btn-primary btn-flat"'); ?>

                            <?php //echo anchor('backend/products/newprice/'.$shop["id"],'一键改价','class="btn btn-sm btn-warning btn-flat"'); ?>


                            <?php // echo anchor('admin/category','采集产品','class="btn btn-sm btn-warning btn-flat"'); ?>
                            <?php // echo anchor('admin/tbshop/descreplace/'.$shop["id"].'?pagetype=replace2','导入产品','class="btn btn-sm bg-olive btn-flat"');?>
                            <?php echo anchor('backend/products/transoption/' . $shop["id"], '属性翻译', 'class="btn btn-sm bg-maroon btn-flat"'); ?>
                            <?php // echo anchor('backend/products/titlereplace/'.$shop["id"].'?pagetype=title3','推送产品','class="btn btn-sm bg-navy btn-flat"'); ?>

                            <?php echo anchor('backend/products/clean/' . $shop["id"], '清理商品', 'class="btn btn-sm btn-warning btn-flat"'); ?>

                            <input type="button" class="btn btn-sm bg-navy btn-flat" value="推送当前所有" id="pushall">

                        <?php endif; ?>
                    </div>


                    <div class="pull-right" style="margin-right:15px;">
                        <?php echo form_open(current_url(), array('class' => 'form-inline', 'method' => 'get', 'id' => 'search_goods')); ?>

                        <div class="form-group" style="margin-right:15px;">
                            <?php echo form_input($keyword); ?>
                        </div>
                        <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-sm btn-primary btn-flat', 'content' => "搜索产品")); ?>

                        <a href="/backend/products/editgoods/0?catid=<?php echo $shop["id"]; ?>"
                           class="btn btn-sm btn-info btn-flat">添加商品</a>

                        <?php
                        $alisummary = json_decode($shop["alisummary"], true);
                        if ($alisummary):
                            ?>
                            <span class="btn btn-sm btn-flat bg-olive" id="alisummary" data-toggle="modal"
                                  data-target="#myModal">查看统计</span>
                        <?php
                        endif;
                        ?>
                        <span class="btn btn-sm btn-flat btn-success" id="startalisummary">后台统计</span>
                        <?php echo form_close(); ?>
                    </div>


                </div>


                <div class="filter">
                    <div class="box" style="padding:10px;margin-top:15px;">

                        <dl>
                            <dt>产品价格</dt>
                            <dd class="form-inline">
                                <input type="number" value="<?php echo $filter["price_min"]; ?>" id="price_min"
                                       placeholder="$" class="form-control input-sm"> - <input type="number"
                                                                                               placeholder="$"
                                                                                               value="<?php echo $filter["price_max"]; ?>"
                                                                                               class="form-control input-sm "
                                                                                               id="price_max">
                                <button id="filterprice" class="btn btn-sm btn-primary btn-flat">确定</button>
                            </dd>
                        </dl>


                        <dl>
                            <dt>速卖通分类</dt>
                            <dd class="form-inline" style="line-height:40px;">
                                <?php
                                if ($alicategoey):
                                    ?>
                                    <select id="alicategory2" name="alicategory2" class="form-control input-sm">
                                        <option value="">选择分类</option>
                                        <?php
                                        foreach ($alicategoey as $cat) {
                                            if ($filter["alicategory"] == $cat["ids"]) {
                                                $selected = " selected";
                                            } else {
                                                $selected = "";
                                            }
                                            echo '<option value="' . $cat["ids"] . '" ' . $selected . '>' . $cat["name"] . '</option>';
                                        }
                                        ?>
                                    </select><br/>
                                <?php
                                endif;
                                ?>

                                <input type="text" value="<?php echo $filter["alicategory"]; ?>" id="alicategory"
                                       placeholder="多个分类用,隔开" class="form-control input-sm" style="width:70%;">
                                <button id="filteralicat" class="btn btn-sm btn-primary btn-flat">确定</button>
                            </dd>
                        </dl>
                        <dl>
                            <dt>适应季节</dt>
                            <dd>
                                <a href="" onclick="return filter('sesson',0);" rel="" name="mode"
                                   class="all<?php if ($filter["sesson"] == 0) echo ' on'; ?>">全部</a>
                                <a href="" onclick="return filter('sesson',1);" rel="" name="mode"
                                   class="sx_child<?php if ($filter["sesson"] == 1) echo ' on'; ?>">春</a>
                                <a href="" onclick="return filter('sesson',2);" rel="" name="mode"
                                   class="sx_child<?php if ($filter["sesson"] == 2) echo ' on'; ?>">夏</a>
                                <a href="" onclick="return filter('sesson',3);" rel="" name="mode"
                                   class="sx_child<?php if ($filter["sesson"] == 3) echo ' on'; ?>">秋</a>
                                <a href="" onclick="return filter('sesson',4);" rel="" name="mode"
                                   class="sx_child<?php if ($filter["sesson"] == 4) echo ' on'; ?>">冬</a>
                            </dd>
                        </dl>

                        <dl>
                            <dt>产品类别</dt>
                            <dd>
                                <a href="" onclick="return filter('collection','');" rel="" name="mode"
                                   class="all<?php if ($filter["collection"] == '') echo ' on'; ?>">全部</a>
                                <?php
                                if ($collection):
                                    foreach ($collection as $ct) {
                                        if ($filter["collection"] == $ct['collection']) {
                                            $css = ' on';
                                        } else {
                                            $css = '';
                                        }
                                        echo '<a href="" onclick="return filter(\'collection\',\'' . $ct["collection"] . '\');" rel="" name="mode" class="sx_child' . $css . '">' . $ct["collection"] . '</a>';
                                    }
                                endif;
                                ?>
                            </dd>
                        </dl>


                        <dl>
                            <dt>发布时间</dt>
                            <dd>
                                <a href="" onclick="return filter('pastday',0);" rel="全部" name="date"
                                   class="all <?php if ($filter["pastday"] == 0) echo 'on'; ?>">全部</a>
                                <a href="" onclick="return filter('pastday',1);" rel="最近一天" name="date"
                                   class="sx_child <?php if ($filter["pastday"] == 1) echo 'on'; ?>">最近一天</a>
                                <a href="" onclick="return filter('pastday',3);" rel="最近三天" name="date"
                                   class="sx_child <?php if ($filter["pastday"] == 3) echo 'on'; ?>">最近三天</a>
                                <a href="" onclick="return filter('pastday',7);" rel="最近一周" name="date"
                                   class="sx_child <?php if ($filter["pastday"] == 7) echo 'on'; ?>">最近一周</a>
                                <a href="" onclick="return filter('pastday',14);" rel="最近两周" name="date"
                                   class="sx_child <?php if ($filter["pastday"] == 14) echo 'on'; ?>">最近两周</a>
                            </dd>
                        </dl>

                        <dl>
                            <dt>推送次数</dt>
                            <dd>
                                <a href="" onclick="return filter('push',0);" rel="全部" name="date"
                                   class="all <?php if ($filter["push"] == 0) echo 'on'; ?>">全部</a>
                                <a href="" onclick="return filter('push',1);" rel="最近一天" name="date"
                                   class="sx_child <?php if ($filter["push"] == 1) echo 'on'; ?>">零次</a>
                                <a href="" onclick="return filter('push',2);" rel="最近三天" name="date"
                                   class="sx_child <?php if ($filter["push"] == 2) echo 'on'; ?>">一次</a>
                                <a href="" onclick="return filter('push',3);" rel="最近一周" name="date"
                                   class="sx_child <?php if ($filter["push"] == 3) echo 'on'; ?>">二次</a>
                                <a href="" onclick="return filter('push',4);" rel="最近一周" name="date"
                                   class="sx_child <?php if ($filter["push"] == 4) echo 'on'; ?>">三次</a>
                                <a href="" onclick="return filter('push',5);" rel="最近两周" name="date"
                                   class="sx_child <?php if ($filter["push"] == 5) echo 'on'; ?>">三次以上</a>
                            </dd>
                        </dl>

                        <dl>
                            <dt>产品排序</dt>
                            <dd>
                                <a href="" onclick="return filter('sort','id_desc');" rel="" name="stage"
                                   class="all<?php if ($filter["sort"] == 'id_desc') echo ' on'; ?>">默认</a>
                                <a href="" onclick="return filter('sort','price_desc');" rel="" name="stage"
                                   class="sx_child<?php if ($filter["sort"] == 'price_desc') echo ' on'; ?>">价格从高到低</a>
                                <a href="" onclick="return filter('sort','price_asc');" rel="" name="stage"
                                   class="sx_child<?php if ($filter["sort"] == 'price_asc') echo ' on'; ?>">价格从低到高</a>
                                <a href="" onclick="return filter('sort','sales_desc');" rel="" name="stage"
                                   class="sx_child<?php if ($filter["sort"] == 'sales_desc') echo ' on'; ?>">来源销量从高到低</a>
                                <a href="" onclick="return filter('sort','sales_asc');" rel="" name="stage"
                                   class="sx_child<?php if ($filter["sort"] == 'sales_asc') echo ' on'; ?>">来源销量从低到高</a>
                                <a href="" onclick="return filter('sort','sellcount_desc');" rel="" name="stage"
                                   class="sx_child<?php if ($filter["sort"] == 'sellcount_desc') echo ' on'; ?>">销量从高到低</a>
                                <a href="" onclick="return filter('sort','sellcount_asc');" rel="" name="stage"
                                   class="sx_child<?php if ($filter["sort"] == 'sellcount_asc') echo ' on'; ?>">销量从低到高</a>
                            </dd>
                        </dl>

                    </div>

                </div>


                <div class=" pull-right form-inline" style="line-height:30px;margin:10px;padding-bottom:15px;">
                    <?php echo '共' . $total . '条产品，' . $page . '/' . $pages . '页'; ?>

                    <select class="form-control input-sm pagesize" style="height:22px;">
                        <option value="0">每页数量</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                        <option value="200">200</option>
                        <option value="500">500</option>
                    </select>

                    <input type="text" id="topage" value="" class="form-control input-sm topage" placeholder='页码'
                           style="margin:0 5px;height:22px;width:45px;">
                    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-xs btn-primary btn-flat jumpbtn', 'id' => 'jumpbtn', 'content' => "跳转")); ?>
                </div>

                <?php echo form_open(current_url(), array('class' => 'form-inline', 'method' => 'post', 'id' => 'batch_goods')); ?>


                <table class="table table-striped table-hover" style="margin-top:20px;border-top:1px solid #ececec;">
                    <thead>
                    <tr>
                        <th>ID</th>
                        <?php if ($pagesize <= 100): ?>
                            <th width="100" class="text-center">图片</th>
                        <?php endif; ?>
                        <th>产品名称</th>
                        <th>来源</th>
                        <th>价格</th>
                        <th>来源销量</th>
                        <th>评论数</th>
                        <th>我的销量</th>
                        <th>推送次数</th>
                        <th>添加时间</th>
                        <th>ALI</th>
                        <?php if ($shop["islock"] == 0): ?>
                            <th>操作</th>
                        <?php endif; ?>
                    </tr>
                    </thead>
                    <tbody>
                    <?php foreach ($loglist as $item): ?>
                        <tr itemid="<?php echo $item["id"]; ?>" <?php if ($item["push"] > 0) {
                            echo 'style="background-color:#dff0d8;"';
                        } else if ($item["edittime"]) {
                            echo 'style="background-color:#EFFFD7;"';
                        } ?>>
                            <td><?php echo $item["id"]; ?></td>
                            <?php if ($pagesize <= 100): ?>
                                <td class="imgcol">
                                    <?php
                                    if (isset($item["thumb"]) && $item["thumb"]) {


                                        $thumb = unserialize($item["thumb"]);
                                        if ($thumb):
                                            $nametag = "";
                                            ?>
                                            <img data-original="<?php
                                            if (strstr($thumb[0], 'images/')) {
                                                echo '/upload/' . $thumb[0];
                                            } else {
                                                echo $thumb[0];
                                            }; ?>" height="80" class="lazy"/>

                                        <?php
                                        else:
                                            if (strstr($item["option"], "http"))
                                                $nametag = "";
                                            else
                                                $nametag = " <span class='label label-danger'>没有图片</span>";
                                        endif;
                                    } else {
                                        $nametag = " <span class='label label-danger'>没有图片</span>";
                                    }
                                    ?>
                                </td>
                            <?php endif; ?>
                            <td><span class="editname"><?php echo $item["name"] . $nametag; ?></span></td>
                            <td><?php if ($item["source"] && $item["source_url"]): ?><a
                                    href="<?php echo $item["source_url"]; ?>"
                                    target="_blank"><?php echo $item["source"]; ?></a><?php else: ?>未知<?php endif; ?>
                            </td>
                            <td><?php echo $item["price"]; ?></td>
                            <td><?php echo $item["sales"]; ?></td>
                            <td><?php echo $item["reviews"]; ?></td>
                            <td><?php echo $item["sellcount"]; ?></td>
                            <td><?php echo $item["push"]; ?></td>
                            <td><?php echo date("y-m-d H:i:s", strtotime($item["addtime"])); ?></td>
                            <td><?php echo $item["rcatid"]; ?></td>
                            <?php if ($shop["islock"] == 0): ?>
                                <td> <?php echo anchor('backend/products/editgoods/' . $item["id"], '<i class="fa fa-edit fa-lg"></i>', 'class="btn btn-xs btn-info btn-flat" target="_blank"'); ?>
                                    &nbsp&nbsp
                                    <span class="btn btn-xs btn-flat btn-danger btn-delete"
                                          itemid="<?php echo $item["id"]; ?>"><i class="fa fa-trash-o fa-lg"></i></span>
                                </td>
                            <?php endif; ?>
                        </tr>
                    <?php endforeach; ?>

                    </tbody>
                </table>
                <input type="hidden" name="formaction" id="formaction" value="">
                <input type="hidden" name="shopid" id="shopid" value="">
                <input type="hidden" name="dump" id="dump" value="0">
                <?php echo form_close(); ?>

                <?php
                if (empty($loglist)) {
                    echo "<h2 style='text-align:center;padding:50px 0;'>没有查询到数据</h2>";
                }
                ?>
                <?php echo $pager; ?>

                <div class=" pull-right form-inline" style="line-height:30px;margin-top:25px;">
                    <?php echo '共' . $total . '条产品，' . $page . '/' . $pages . '页'; ?>

                    <select class="form-control input-sm pagesize" style="height:22px;">
                        <option value="0">每页数量</option>
                        <option value="50">50</option>
                        <option value="100">100</option>
                        <option value="200">200</option>
                        <option value="500">500</option>
                    </select>

                    <input type="text" id="topage" value="" class="form-control input-sm topage" placeholder='页码'
                           style="margin:0 5px;height:22px;width:45px;">
                    <?php echo form_button(array('type' => 'submit', 'class' => 'btn btn-xs btn-primary btn-flat jumpbtn', 'id' => 'jumpbtn', 'content' => "跳转")); ?>
                </div>


            </div>
        </div>
    </div>
</div>
<?php
if ($alisummary):
    ?>
    <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                    <h4 class="modal-title" id="myModalLabel">查看阿里分类产品统计</h4>
                </div>
                <div class="modal-body">
                    <h4>统计时间 <?php echo $alisummary["update"]; ?></h4>


                    <?php

                    $result = sortarray($alisummary["list"], "count");
                    $newresult = [];
                    foreach ($result as $k => $s) {
                        if (strstr($s["name"], "&")) {
                            $tmp = explode("&", $s["name"]);
                            $flevel = trim($tmp[0]);
                            if (isset($newresult[$flevel])) {
                                $newresult[$flevel]["sub"][] = $s;
                                $newresult[$flevel]["count"] += $s["count"];
                            } else {
                                $newresult[$flevel] = [
                                    "sub" => [$s],
                                    "count" => $s["count"],
                                    "count2" => 0
                                ];
                            }
                            if (isset($s["count2"])) {
                                $newresult[$flevel]["count2"] += $s["count2"];
                            }

                            unset($result[$k]);
                        }
                    }
                    $itemcount = 0;
                    foreach ($newresult as $name => $item):
                        $itemcount++;
                        ?>

                        <div class="panel-group">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h4 class="panel-title">
      <span class="pull-right badge"><?php
          if (isset($item["count2"])) echo $item["count2"] . "/";
          echo $item["count"]; ?></span>

                                        <a data-toggle="collapse"
                                           href="#collapse_<?php echo $itemcount; ?>"><?php echo $name; ?></a>
                                    </h4>
                                </div>
                                <div id="collapse_<?php echo $itemcount; ?>" class="panel-collapse collapse">
                                    <ul class="list-group alisummarylist">
                                        <?php foreach ($item["sub"] as $item2): ?>
                                            <li class="list-group-item" style="cursor:pointer">
                                <span class="badge"><?php
                                    if (isset($item2["count2"])) echo $item2["count2"] . "/";
                                    echo $item2["count"]; ?></span>
                                                <span class="ccname"><?php echo $item2["name"]; ?></span>
                                            </li>
                                        <?php endforeach; ?>
                                    </ul>
                                </div>
                            </div>
                        </div>


                    <?php
                    endforeach;
                    foreach ($result

                    as $item): ?>
                    <ul class="list-group alisummarylist" id="alisummarylist">
                        <li class="list-group-item" style="cursor:pointer">
                    <span class="badge"><?php
                        if (isset($item["count2"])) echo $item["count2"] . "/";
                        echo $item["count"]; ?></span>
                            <span class="ccname"><?php echo $item["name"]; ?></span>
                        </li>
                        <?php endforeach;
                        ?>

                    </ul>

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>
<?php
endif;
?>
<script>

    window.addEventListener('DOMContentLoaded', function () {
        (function ($) {
            $(document).ready(function () {
                // Init iCheck
                var elem_input = $('input');
                if (elem_input.length) {
                    elem_input.iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_square-blue'
                    });
                }

            });
        })(jQuery);
    });

    $(function () {
        require(['jquery', 'clipboard.min'], function ($, clipboardlib) {
            var clipboard = new clipboardlib('.copybtn');
            clipboard.on('success', function (e) {
                layer.msg("复制成功");
            });
            clipboard.on('error', function (e) {
                layer.msg("复制失败");
            });
        });
    });
</script>


<script src="/assets/backend/lazyload.js?v=1.9.1"></script>
<script>
    $(document).ready(function () {
        $("img.lazy").lazyload({effect: "fadeIn"});

        $("#alicategory2").select2();

        $("#alicategory2").on("select2:select", function () {
            var data = $(this).val();
            $("#alicategory").val(data);
        });

        $("body").on("click", "ul.alisummarylist li", function () {
            var searchtext = $(this).find("span.ccname").text();
            var selectval = "";
            var findval = 1;
            $('#alicategory2 option').each(function () {
                if ($(this).text().trim() == searchtext) {
                    selectval = $(this).attr("value");
                    findval = 2;
                }
            });
            if (findval == 2) {
                $('#alicategory2').val(selectval).trigger("change");
                ;
                $("#alicategory").val(selectval);
            } else {
                $("#alicategory").val(searchtext);
            }
            $('#myModal').modal('hide');
        });

        $("span#startalisummary").on("click", function () {
            shadow = layer.load(1, {
                shade: [0.1, '#000']
            });
            $.post("/backend/crons/summary", {"catid":<?php echo $shop["id"] ? $shop["id"] : 0;?>}, function (result) {
                layer.close(shadow);
                layer.msg("任务已经后台运行，完成后可在后台直接查看");
            }, dataType = "json");
        });
    });
</script>
<script>

    var isedit = 0;
    $('span.editname').on("dblclick", function () {
        if (isedit == 1) {
            return;
        } else {
            isedit = 1;
        }
        var obj = this;
        var oldHtml = $(this).html();
        var newobj = document.createElement('input');
        newobj.name = "name";
        newobj.type = "text";
        newobj.setAttribute("class", "form-control input-sm");
        newobj.setAttribute("style", "width:100%");
        newobj.value = oldHtml;
        var cid = $(this).parent().parent().attr("itemid");
        $(this).html('');
        this.appendChild(newobj);
        newobj.focus();


        $(newobj).keydown(function (event) {
            if (event.keyCode == 13) {
                $(this).trigger("blur");
                event.preventDefault();
            }

        });

        $(newobj).blur(function () {

            if (this.value == null || this.value == "") {
                $(obj).html(oldHtml);
                isedit = 0;
                return false;
            }
            var newhtml = this.value ? this.value : oldHtml;
            $(obj).html(newhtml);

            if (oldHtml != this.value) {
                $.ajax({
                    type: "post",
                    url: "/backend/products/goodsajaxedit",
                    dataType: "json",
                    data: {"attrName": "name", "newHtml": this.value, "cid": cid},
                    error: function () {
                        isedit = 0;
                    },
                    success: function () {
                        isedit = 0;
                    },
                });
            } else {
                isedit = 0;
            }

        })
    });


    $("span.btn-delete").on("click", function (event) {
        var cid = $(this).attr("itemid");
        var row = $(this).parent().parent();
        layer.confirm("确认要删除吗，删除将无法回复？", {title: "确认"}, function (index) {
            $.ajax({
                type: "post",
                url: "/backend/products/goodsajaxdel",
                dataType: "json",
                data: {"cid": cid},
                error: function () {
                },
                success: function (result) {
                    if (result["status"] == 1) {
                        row.remove();
                    } else {
                        layer.msg(result["msg"]);
                    }
                },
            });
            layer.close(index);
        });

    });


    $(function () {

        function initTableCheckbox() {
            var $thr = $('table thead tr');
            var $checkAllTh = $('<th><input type="checkbox" id="checkAll" name="checkAll" /></th>');
            $thr.prepend($checkAllTh);
            $('#checkAll').on('ifChecked ifUnchecked', function (event) {
                $tbr.find('input').each(function () {
                    $(this).iCheck('toggle');
                    $(this).parent().parent().toggleClass('warning');
                });
            });
            var $tbr = $('table tbody tr');
            var $checkItemTd = $('<td><input type="checkbox" name="checkItem[]" /></td>');
            $tbr.prepend($checkItemTd);

            $tbr.find('input').on('ifChecked ifUnchecked', function (event) {
                $(this).val($(this).parent().parent().parent().attr("itemid"));
                $(this).parent().parent().parent().toggleClass('warning');
                /*
                $checkAll.prop('checked',$tbr.find('input:checked').length == $tbr.length ? true : false);
                */
            });
            $tbr.click(function () {
                $(this).find('input').iCheck('toggle');
            });
        }

        initTableCheckbox();

        $("#batchdel").on("click", function () {
            var checkcount = 0;
            $("table tbody").find("input").each(function () {
                if ($(this).prop('checked')) {
                    checkcount = checkcount + 1;
                }
            });

            if (checkcount == 0) {
                layer.alert('没有选中任何数据');
                return;
            }

            layer.confirm("确认要删除吗，删除后不能恢复", {title: "删除确认"}, function (index) {
                layer.close(index);
                $("#formaction").val("delete");
                $("form#batch_goods").submit();
            });
        });
        <?php
        $shophtml = "";
        foreach ($myshops as $sshop) {
            $shophtml .= "<option value=\"" . $sshop["id"] . "\">" . str_replace("'", "&#39;", $sshop["name"]) . "</option>";
        }
        ?>

        $("#batchtrans").on("click", function () {
            var checkcount = 0;
            $("table tbody").find("input").each(function () {
                if ($(this).prop('checked')) {
                    checkcount = checkcount + 1;
                }
            });
            if (checkcount == 0) {
                layer.alert('没有选中任何数据');
                return;
            }

            layer.open({
                type: 1,
                title: '选择需要转移的分类',
                closeBtn: 1,
                shadeClose: true,
                skin: 'layui-layer-lan',
                content: '<div style="padding:20px 30px;"><div class="layui-layer-content" style="margin-bottom:10px;"><select class="form-control" id="transid"><?php echo $shophtml;?></select><br/><input type="checkbox" name="dump" id="isdump"> 是否复制产品</div><div class="layui-layer-btn layui-layer-btn-"><a class="layui-layer-btn0" onclick=\'$("#formaction").val("trans");if($("#isdump").is(":checked")){$("#dump").val(1)}$("#shopid").val($("#transid").val());$("form#batch_goods").submit();\'>确定</a></div></div>'
            });
            $('#transid').select2();
        });

        $("#batchtag").on("click", function () {
            var checkcount = 0;
            $("table tbody").find("input").each(function () {
                if ($(this).prop('checked')) {
                    checkcount = checkcount + 1;
                }
            });
            if (checkcount == 0) {
                layer.alert('没有选中任何数据');
                return;
            }

            layer.open({
                type: 1,
                title: '选择需要标记选项',
                skin: 'layui-layer-rim',
                closeBtn: 1,
                shadeClose: true,
                content: '<div style="padding:20px 30px;"><div class="layui-layer-content" style="margin-bottom:10px;"><div class="form-group"><input type="text" name="diytype" placeholder="自定义类别" class="form-control input-sm "></div><div class="form-group"><label><input type="checkbox" name="session[]" value="春"/> 春 </label> <label><input type="checkbox" name="session[]" value="夏"/> 夏 </label><label><input type="checkbox" name="session[]" value="秋"/> 秋 </label> <label><input type="checkbox" name="session[]" value="冬"/> 冬 </label></div><div class="form-group"><button id="acttag" class="btn btn-flat btn-info">批量标记</button></div></div></div>'
            });

        });

        <?php
        $site_string = "";
        foreach ($sites as $site) {
            $site_string .= '<option value="' . $site["id"] . '">' . $site["name"] . '</option>';
        }
        echo "var site_string = '{$site_string}';"
        ?>
        $("#batchpush").on("click", function () {
            var checkcount = 0;
            $("table tbody").find("input").each(function () {
                if ($(this).prop('checked')) {
                    checkcount = checkcount + 1;
                }
            });
            if (checkcount == 0) {
                layer.alert('没有选中任何数据');
                return;
            }

            layer.open({
                type: 1,
                title: '选择需要推送的站点和分类',
                skin: 'layui-layer-rim',
                closeBtn: 1,
                shadeClose: true,
                content: '<div style="padding:20px 30px;"><div class="layui-layer-content" style="margin-bottom:10px;"><div class="form-group"><select name="siteid" id="siteid" style="width:300px;"><option value="0">请选择需要推送的站点</option>' + site_string + '</select></div><div class="form-group"><select name="catid" id="catid" style="width:300px;"><option value="0">请选择需要推送的分类</option></select></div><div class="form-group"><button id="actpush" class="btn btn-flat btn-info">批量推送</button></div></div></div>'
            });
            $("#siteid").select2();
            $("#catid").select2();

        });

        $("body").on("change", "#siteid", function () {
            var siteid = $(this).val();
            $.ajax({
                url: "/backend/sites/category/ajaxget/" + siteid,
                dataType: "JSON",
                data: {},
                type: "GET",
                success: function (data) {
                    var gradeNum = data.length;
                    var option = "<option value=''>请选择需要推送的分类</option>";
                    if (gradeNum > 0) {
                        for (var i = 0; i < gradeNum; i++) {
                            option += "<option value='" + data[i].id + "'>" + data[i].name + "</option>";
                            if (data[i]["sub"]) {
                                for (var j = 0; j < data[i]["sub"].length; j++) {
                                    option += "<option value='" + data[i]["sub"][j].id + "'> - " + data[i]["sub"][j].name + "</option>";
                                }
                            }
                        }
                    }
                    $("#catid").html(option);
                    $("#catid").select2({minimumResultsForSearch: -1});//加载样式
                },
                error: function (e) {
                    layer.alert("系统异常，请稍候重试！");
                }
            });
        });

        $("body").on("click", "#actpush", function () {
            if ($("[name=siteid]").val() <= 0) {
                layer.msg("请选择站点");
                return;
            }
            if ($("[name=catid]").val() <= 0) {
                layer.msg("请选择分类");
                return;
            }
            layer.closeAll();
            $("#formaction").val("batchpush");
            $("[name=siteid]").appendTo("form#batch_goods");
            $("[name=catid]").appendTo("form#batch_goods");
            $("[name=vendor]").appendTo("form#batch_goods");
            $("[name=groupnum]").appendTo("form#batch_goods");
            $("[name=ruler]").appendTo("form#batch_goods");
            $("form#batch_goods").submit();
        });

        $("body").on("click", "#pushall", function () {

            layer.open({
                type: 1,
                title: '选择需要推送的站点和分类',
                skin: 'layui-layer-rim',
                closeBtn: 1,
                shadeClose: true,
                content: '<div style="padding:20px 30px;"><div class="layui-layer-content" style="margin-bottom:10px;"><h5>将推送当前条件下所有的商品到指定站点</h5><div class="form-group"><select name="siteid" id="siteid" style="width:300px;"><option value="0">请选择需要推送的站点</option>' + site_string + '</select></div><div class="form-group"><select name="catid" id="catid" style="width:300px;"><option value="0">请选择需要推送的分类</option></select></div><div class="form-group"><button id="actpushall" class="btn btn-flat btn-info">全部推送</button></div></div></div>'
            });
            $("#siteid").select2();
            $("#catid").select2();


        });

        $("body").on("click", "#actpushall", function () {
            if ($("[name=siteid]").val() <= 0) {
                layer.msg("请选择站点");
                return;
            }
            if ($("[name=catid]").val() <= 0) {
                layer.msg("请选择分类");
                return;
            }

            url = window.location.href;
            pcat = url.split("/").pop();

            shadow = layer.load(1, {
                shade: [0.1, '#000']
            });

            $.ajax({
                type: "post",
                url: "/backend/crons/ajaxadd",
                dataType: "json",
                data: {
                    "catid": $("[name=catid]").val(),
                    "vendor": $("[name=vendor]").val(),
                    "groupnum": $("[name=groupnum]").val(),
                    "startindex": $("[name=startindex]").val(),
                    "limits": $("[name=limits]").val(),
                    "siteid": $("[name=siteid]").val(),
                    "ruler": $("[name=ruler]").val(),
                    "jobtype": "pushall",
                    "filter": pcat
                },
                error: function () {
                    layer.msg("系统错误,请联系管理员");
                    layer.close(shadow);
                },
                success: function (data) {
                    if (data.status == 1) {
                        layer.msg("任务添加成功");
                    } else {
                        layer.msg(data.msg);
                    }
                    layer.close(shadow);
                },
            });
            layer.closeAll();

        });


        $("body").on("click", "#acttag", function () {
            $("#formaction").val("tagging");
            $("[name*=session]").appendTo("form#batch_goods");
            $("[name=diytype]").appendTo("form#batch_goods");
            $("form#batch_goods").submit();
        });

        $("#batchshopify").on("click", function () {
            var checkcount = 0;
            $("table tbody").find("input").each(function () {
                if ($(this).prop('checked')) {
                    checkcount = checkcount + 1;
                }
            });
            if (checkcount == 0) {
                layer.alert('没有选中任何数据');
                return;
            }
            $("#formaction").remove();
            $("form#batch_goods").attr("action", "<?php echo site_url('backend/products/shopify/' . $shop["id"]);?>");
            $("form#batch_goods").submit();
        });


        $("select.pagesize").change(function () {
            pagesize = $(this).find("option:selected").val();
            /*pagesize=$("select#pagesize option:selected").val();*/
            if (pagesize > 0) {
                var url = window.location.href;
                var newUrl = changeURLArg(url, "pagesize", pagesize);
                window.location.href = newUrl;
            }
        });
        $(".jumpbtn").on("click", function () {
            topage = $(this).parent().find(".topage").val();
            if (topage > 0) {
                var url = window.location.href;
                var newUrl = changeURLArg(url, "page", topage);
                window.location.href = newUrl;
            }
        });

        $("#hotsale").on("click", function () {
            var url = window.location.href;
            sort = getUrlParam("sort");
            if (!sort) {
                sort = "sales";
            } else if (sort == "sales") {
                sort = "id";
            } else {
                sort = "sales";
            }
            var newUrl = changeURLArg(url, "sort", sort);
            window.location.href = newUrl;
        });
        $("button#filteralicat").on("click", function (event) {
            let val = $("#alicategory").val();
            var url = window.location.href;
            if (val) {
                var url = changeURLArg(url, 'alicategory', val);
            }
            window.location.href = url;
            event.preventDefault();
        });

        $("button#filterprice").on("click", function (event) {
            min = parseInt($("#price_min").val());
            max = parseInt($("#price_max").val());
            if (min < max) {
                if (getUrlParam('price_min') == min && getUrlParam('price_max') == max) {
                    return false;
                }

                var url = window.location.href;
                var newUrl = changeURLArg(url, 'price_min', min);
                var newUrl = changeURLArg(newUrl, 'price_max', max);
                window.location.href = newUrl;
            } else {
                var url = window.location.href;
                var newUrl = changeURLArg(url, 'price_min', '');
                var newUrl = changeURLArg(newUrl, 'price_max', '');
                window.location.href = newUrl;
            }
            event.preventDefault();
        });
    });


    function changeURLArg(url, arg, arg_val) {
        var pattern = arg + '=([^&]*)';
        var replaceText = arg + '=' + arg_val;
        if (url.match(pattern)) {
            var tmp = '/(' + arg + '=)([^&]*)/gi';
            tmp = url.replace(eval(tmp), replaceText);
            return tmp;
        } else {
            if (url.match('[\?]')) {
                return url + '&' + replaceText;
            } else {
                return url + '?' + replaceText;
            }
        }
        return url + '\n' + arg + '\n' + arg_val;
    }

    function getUrlParam(name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    }

    function layerConfirm(msg, t) {
        layer.confirm(msg, function (index) {
            t.onclick = "";
            t.click();
            layer.close(index);
        });
    }

    function filter(name, val) {
        if (getUrlParam(name) == val) {
            return false;
        }
        var url = window.location.href;
        var newUrl = changeURLArg(url, name, val);
        window.location.href = newUrl;
        return false;
    }


</script>